package com.openxt.nbzj.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.openxt.nbzj.R;
import com.openxt.nbzj.adapter.ProjectListAdapter;
import com.openxt.nbzj.fragment.OpenxtBaseActivity;
import com.openxt.nbzj.model.ConfigModel;
import com.openxt.nbzj.model.RemotingModel;
import com.openxt.nbzj.remoting.RemotingEx;
import com.openxt.nbzj.search.SearchEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.StringUtil;
import qs.openxt.libs.util.Utils;

/**
 * Created by 颖杰_2 on 2016-07-19.
 */
public class ProjectActivity extends OpenxtBaseActivity implements RemotingEx.OnActionListener, AdapterView.OnItemClickListener, View.OnClickListener, TextWatcher {
    @BindView(R.id.ptrClassicFrameLayout)
    PtrClassicFrameLayout ptrClassicFrameLayout;
    @BindView(R.id.listView)
    ListView listView;

    @BindView(R.id.search_bar)
    RelativeLayout search_bar;
    @BindView(R.id.search_btn)
    Button search_btn;
    @BindView(R.id.searchEditText)
    SearchEditText searchEditText;

    private Handler mHandler = new Handler();
    private RemotingModel remotingModel = null;
    Context mContext = null;
    ProjectListAdapter projectListAdapter = null;
    List<JSONObject> mList = new ArrayList<>();

    private int pageIndex = 1;
    private int pageSize = 10;
    private int total = 0;
    private Long timeStamp = null;
    private boolean showSearchBar = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setBaseStyle(R.layout.project_activity, "项目信息列表");
        ButterKnife.bind(this);
        setActionUrl("#/project");
        mContext = this;
        remotingModel = new RemotingModel(mContext);

        projectListAdapter = new ProjectListAdapter(mContext, mList);
        listView.setAdapter(projectListAdapter);
        listView.setOnItemClickListener(this);

        search_btn.setEnabled(false);
        searchEditText.addTextChangedListener(this);

        setupRight();

        search_btn.setOnClickListener(this);

        ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            pageIndex = 1;
                            timeStamp = null;
                            ptrClassicFrameLayout.setLoadMoreEnable(false);
                            doLoad();
                        } catch (Exception e) {
                        }
                    }
                }, 10);
            }
        });

        ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            pageIndex++;
                            doLoadMore();
                        } catch (Exception e) {
                        }
                    }
                }, 10);
            }
        });

        initData();
    }

    private void initData(){
        //获取缓存
        final String val = Utils.getLocalStorage(mContext, ConfigModel.PROJECT_GETNATIVE);
        if(!StringUtil.isNull(val)){
            mList.clear();
            projectListAdapter.notifyDataSetChanged();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    try{
                        JSONArray array = JSON.parseArray(val);
                        for(int i = 0, j = array.size(); i < j; i++){
                            pageIndex = i + 1;
                            JSONObject item = array.getJSONObject(i);
                            JSONArray rows = item.getJSONArray("rows");
                            if(rows == null)
                                continue;
                            for(int m = 0, n = rows.size(); m < n; m++){
                                mList.add(rows.getJSONObject(m));
                            }

                            timeStamp = item.getLong("timeStamp");
                            total = item.getInteger("total");
                        }
                        projectListAdapter.notifyDataSetChanged();

                        if(total > (pageIndex * pageSize))
                            ptrClassicFrameLayout.setLoadMoreEnable(true);
                        else
                            ptrClassicFrameLayout.setLoadMoreEnable(false);
                        listView.setAdapter(projectListAdapter);
                    }catch (Exception e){
                    }
                }
            }, 0);
        }else if (ActivityUtil.isNetworkAvailable(mContext)) {
            ptrClassicFrameLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ptrClassicFrameLayout.autoRefresh(true);
                }
            }, 0);
        }
    }

    private void doLoad(){
        try {
            String value = searchEditText.getText().toString();
            JSONObject param = new JSONObject();
            param.put("pageIndex", pageIndex);
            param.put("pageSize", pageSize);
            param.put("timeStamp", StringUtil.isNull(timeStamp) ? "" : timeStamp);
            param.put("name", value);
            remotingModel.getProjectGetNative(this, false, param, null);
        }catch (Exception e){

        }
    }

    private void doLoadMore(){
        try {
            String value = searchEditText.getText().toString();
            JSONObject param = new JSONObject();
            param.put("pageIndex", pageIndex);
            param.put("pageSize", pageSize);
            param.put("timeStamp", StringUtil.isNull(timeStamp) ? "" : timeStamp);
            param.put("name", value);
            remotingModel.getProjectGetNative(this, false, param, "$more");
        }catch (Exception e){

        }
    }

    @Override
    public void onActionCompleted(String reVal, String actionName) {
        try {
            if(pageIndex == 1)
                Utils.removeLocalStorage(mContext, ConfigModel.PROJECT_GETNATIVE);

            JSONObject data = JSON.parseObject(reVal);
            final String val = Utils.getLocalStorage(mContext, ConfigModel.PROJECT_GETNATIVE);
            JSONArray cacheArray = null;
            if (StringUtil.isNull(val)) {
                cacheArray = new JSONArray();
                cacheArray.add(data);
                Utils.setLocalStorage(mContext, ConfigModel.PROJECT_GETNATIVE, cacheArray.toString());
            } else {
                cacheArray = JSON.parseArray(val);
                if (cacheArray.size() < 5) {
                    cacheArray.add(data);
                    Utils.setLocalStorage(mContext, ConfigModel.PROJECT_GETNATIVE, cacheArray.toString());
                }
            }
            total = data.getInteger("total");
            timeStamp = data.getLong("timeStamp");
            JSONArray rows = data.getJSONArray("rows");

            if (ConfigModel.PROJECT_GETNATIVE.equals(actionName)) {
                try {
                    mList.clear();
                    projectListAdapter.notifyDataSetChanged();

                    for (int i = 0, j = rows.size(); i < j; i++){
                        mList.add(rows.getJSONObject(i));
                    }
                    if(total > (pageIndex * pageSize))
                        ptrClassicFrameLayout.setLoadMoreEnable(true);
                    else
                        ptrClassicFrameLayout.setLoadMoreEnable(false);
                    listView.setAdapter(projectListAdapter);
                } finally {
                    ptrClassicFrameLayout.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ptrClassicFrameLayout.refreshComplete();
                            projectListAdapter.notifyDataSetChanged();
                        }
                    }, 0);
                }
            } else if ((ConfigModel.PROJECT_GETNATIVE + "$more").equals(actionName)) {
                try {
                    for (int i = 0, j = rows.size(); i < j; i++){
                        mList.add(rows.getJSONObject(i));
                    }
                    if(total > (pageIndex * pageSize))
                        ptrClassicFrameLayout.setLoadMoreEnable(true);
                    else
                        ptrClassicFrameLayout.setLoadMoreEnable(false);
                } finally {
                    ptrClassicFrameLayout.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if(total > (pageIndex * pageSize))
                                ptrClassicFrameLayout.loadMoreComplete(true);
                            else
                                ptrClassicFrameLayout.loadMoreComplete(false);
                            projectListAdapter.notifyDataSetChanged();
                        }
                    }, 0);
                }
            }
        }catch (Exception e){

        }
    }

    @Override
    public void onActionFailed(String errorVal, String actionName) {
        if ((ConfigModel.PROJECT_GETNATIVE + "$more").equals(actionName)){
            pageIndex--;
        }
        ptrClassicFrameLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrClassicFrameLayout.refreshComplete();
            }
        }, 0);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        try {
            if (!ActivityUtil.isNetworkAvailable(mContext)) {
                showMsg("无网络，请先查看网络是否正常打开");
                return;
            }

            Bundle bundle = new Bundle();
            JSONObject item = mList.get(position);
            String ID = item.getString("ID");
            bundle.putString("ID", ID);
            toActivity(ProjectDetailsActivity.class, bundle, false);
        }catch (Exception e){

        }
    }

    private void setupRight() {
        LinearLayout right = getRight();
        right.setVisibility(View.VISIBLE);
        right.removeAllViews();

        View view = LayoutInflater.from(this).inflate(R.layout.right_btn, null);
        view.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));
        right.addView(view);

        ImageView btn = (ImageView)view.findViewById(R.id.right_btn);
        btn.setImageResource(R.mipmap.search);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideInputMethod();
                showSearchBar = !showSearchBar;
                search_bar.setVisibility(showSearchBar ? View.VISIBLE : View.GONE);
            }
        });
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.search_btn){
            hideInputMethod();
            if (ActivityUtil.isNetworkAvailable(mContext)) {
                ptrClassicFrameLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            ptrClassicFrameLayout.setLoadMoreEnable(false);
                            ptrClassicFrameLayout.loadMoreComplete(false);
                            ptrClassicFrameLayout.autoRefresh(true);
                        }catch (Exception e){

                        }
                    }
                }, 0);
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if(StringUtil.isNull(s))
            search_btn.setEnabled(false);
        else
            search_btn.setEnabled(true);
    }
}
